package com.github.avatar.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.avatar.config.Constants;
import com.github.avatar.model.Result;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Jerry Liu
 * @since 2017/4/10
 */
public class HttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * get请求
     * @param url 请求地址
     * @param type 解析body返回的对象
     * @param <T> 泛型
     * @return 返回的对象
     */
    public static <T> Result<T> performGet(String url, TypeReference<Result<T>> type) {
        HttpClient httpClient = HttpClientManager.getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        return parseResponse(httpClient, httpGet, type);
    }


    /**
     * post请求
     * @param url 请求地址
     * @param param 参数
     * @param type 解析body返回的对象
     * @param <T> 泛型
     * @return 返回的对象
     */
    public static <T> Result<T> performPost(String url, Object param, TypeReference<Result<T>> type) {
        HttpClient httpClient = HttpClientManager.getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(JSON.toJSONString(param), Constants.UTF_8);
        entity.setContentType(Constants.APPLICATION_JSON);
        entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, Constants.APPLICATION_JSON));
        httpPost.setEntity(entity);

        return parseResponse(httpClient, httpPost, type);
    }

    private static <T> Result<T> parseResponse(HttpClient httpClient,
                                               HttpUriRequest request,
                                               TypeReference<Result<T>> type) {
        try {
            return httpClient.execute(request, httpResponse -> {
                StatusLine statusLine = httpResponse.getStatusLine();
                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = httpResponse.getEntity();
                    String content = EntityUtils.toString(entity, Constants.UTF_8);
                    return JSON.parseObject(content, type);
                }
                return null;
            });
        } catch (IOException e) {
            logger.error("Request remote host error!");
        }
        return null;
    }
}
